//
//  PxHomeViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxNotifyListViewController.h"
#import "PxFormValidate.h"

@implementation PxNotifyListViewController {
    BOOL isSelected;
    NSArray *smsModelArray;
    BOOL isContinues;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        isContinues = NO;
        isSelected = NO;
        smsModelArray = [PxGlobal getData:SMSMODEL_INFO];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setLogoTitleViewWithTitle:@"通知发送"];
    self.dataSource = [PxGlobal selectTable:TABLE_SCHOOL withData:nil];
    
    CGFloat height = CGRectGetHeight(self.view.bounds);
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    CGFloat tableHeight = height - [PxGlobal getCustomerHeight:40] - 64;
//    if (self.dataSource.count*45 < tableHeight)
//        tableHeight = self.dataSource.count*45;
    self.tableView.height = tableHeight;
    [self.view addSubview:self.tableView];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorColor = [UIColor colorWithHTMLStr:@"d0d0d0"];
    self.tableView.allowsMultipleSelection = YES;
    
    [self setRightBtn:isSelected];
    [self setBottomBtn];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)setRightBtn:(BOOL) isAllSelected
{
    UIButton *navBarRightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [navBarRightButton addTarget:self action:@selector(navBarRightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [navBarRightButton setContentMode:UIViewContentModeCenter];
    
    if (isAllSelected)
        [navBarRightButton setTitle:@"取消"];
    else
        [navBarRightButton setTitle:@"全选"];
    
    navBarRightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    UIColor *color1 = [UIColor colorWithHTMLStr:@"ff4e08"];
    [navBarRightButton setTitleColor:color1 forState:UIControlStateNormal];
    
    UIBarButtonItem *rightButtonItem=[[UIBarButtonItem alloc] initWithCustomView:navBarRightButton];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    if([LLYTSmallUtil iOSBigVersion] >= 6.5)
        negativeSpacer.width = -9;// it was -6 in iOS 6
    else
        negativeSpacer.width = 1;
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,rightButtonItem/*this will be the button which u actually need*/, nil] animated:NO];
}

-(void)setBottomBtn
{
    CGFloat top = self.view.height - [PxGlobal getCustomerHeight:40] - 64;
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat height = [PxGlobal getCustomerHeight:40];
    btn2.frame = CGRectMake(0, top, CGRectGetWidth(self.view.frame), height);
    [btn2 setSelector:@selector(showSMSModel) withTarget:self];
    [btn2 setTitle:@"发送短信"];
    [btn2 setTitleColor:[UIColor colorWithHTMLStr:@"ffffff"] forState:UIControlStateNormal];
    btn2.titleLabel.font = [UIFont systemFontOfSize:18];
    btn2.backgroundColor = [UIColor colorWithHTMLStr:@"ff4e08"];
    [self.view addSubview:btn2];
}

-(void)showSMSModel
{
    NSMutableArray *arr = [NSMutableArray new];
    for (NSDictionary *data in smsModelArray) {
        [arr addObject:data[@"name"]];
    }
    if (!_pickViewController) {
        _pickViewController = [[PxAlertPickViewController alloc] initWithDataSource:arr];
        _pickViewController.delegate = self;
        _pickViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        _pickViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        _pickViewController.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    }
    [self presentViewController:_pickViewController animated:YES completion:nil];
}

- (void)buttonClick:(NSInteger)row
{
    if (smsModelArray.count > 0) {
        NSDictionary *data = smsModelArray[row];
        [self notify:data[@"id"]];
    } else {
        [self notify:@"1"];
    }
}

-(void)notify:(NSString *)smsModelId
{
    NSMutableArray *records = [NSMutableArray new];
    NSArray *arrays = [self.tableView indexPathsForSelectedRows];
    for (NSIndexPath *indexPath in arrays) {
        NSDictionary *dic = self.dataSource[indexPath.row];
        [records addObject:dic];
    }
    if (records.count == 0)
        return;
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_SMS_SEND;
    
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:records, @"records", smsModelId, @"smsModelId", nil];
    
    [cmd.paramDic addEntriesFromDictionary:data];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:@"通知已发送"];
        for (NSDictionary *data in records) {
            int selectId = [data[@"id"] intValue];
            [PxGlobal deleteTabel:TABLE_SCHOOL withID:selectId];
        }
        if (arrays.count == self.dataSource.count) {
            [self popToLastControllerWithIncomingParam:nil];
        } else {
            for (NSIndexPath *indexPath in arrays) {
                [self.dataSource removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            }
        }
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        
        [LLAlertService sysAlertWithTip:dic[RESULT_DESC] withTitle:@"错误"];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)navBarRightBtnAction
{
    isSelected = !isSelected;
    [self setRightBtn:isSelected];
    for (int row=0; row<self.dataSource.count; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        if (isSelected)
            [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        else
            [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
        [self clickCell:indexPath];
    }
}

-(void)clickCell:(NSIndexPath *)indexPath
{
    PxEditableTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [self.view resignFirstResponder];
    if(cell.isSelected) {
        cell.imageView.image = [UIImage imageNamed:@"Images/icon-Choose"];
    } else {
        cell.imageView.image = [UIImage imageNamed:@"Images/icon-umChoose"];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dataChanged:(NSIndexPath *)indexPath andValue:(NSString *)value
{
    NSMutableDictionary *dic = self.dataSource[indexPath.row];
    [dic setObject:value forKey:@"phone"];
    // 更新dataSource
    [self.dataSource removeObjectAtIndex:indexPath.row];
    [self.dataSource insertObject:dic atIndex:indexPath.row];
    // 更新数据库
    [PxGlobal updateTable:TABLE_SCHOOL withData:dic];
}

#pragma mark tableview delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataSource[indexPath.row];
    static NSString *cellIdentifier = @"cellIdentifier";
    PxEditableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[PxEditableTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
        cell.delegate = self;
        cell.indexPath = indexPath;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.imageView.image = [UIImage imageNamed:@"Images/icon-umChoose"];
        cell.textLabel.text = [PxGlobal getDicValue:@"phone" fromDic:dic];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = [UIColor colorWithHTMLStr:@"4c4c4c"];
        cell.detailTextLabel.text = [PxGlobal getDicValue:@"sendTime" fromDic:dic];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
        cell.detailTextLabel.textColor = [UIColor colorWithHTMLStr:@"9c9c9c"];
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self clickCell:indexPath];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self clickCell:indexPath];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSDictionary *dic = [self.dataSource objectAtIndex:indexPath.row];
        int selectId = [dic[@"id"] intValue];
        [PxGlobal deleteTabel:TABLE_SCHOOL withID:selectId];
        [self.dataSource removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

@end
